<template>
  <div style="transform: none;">
    <div class="titletopXX">
      <van-nav-bar
        size="30"
        :title="title"
        left-arrow
        right-text=""
        :fixed="true"
        @click-left="onClickLeft"
      />
    </div>
    <div class="content">
      <van-form @submit="onSubmit">
        <van-cell-group>
          <van-field
            style="height: 60px"
            label="行程标题"
            v-model="formData.name"
            name="name"
            placeholder="请填写行程标题"
            required
            :rules="[{ required: true, message: '请填写行程标题信息' }]"
          />
          <van-field
            style="height: 130px"
            name="uploader"
            label="行程封面图"
            required
            @click="selectImg('one')"
          >
            <template #input>
              <van-image width="120" height="100" :src="formData.image" />
            </template>
          </van-field>
          <van-field
            label="行程介绍"
            style="height: 60px"
            v-model="formData.description"
            name="description"
            placeholder="请填写行程介绍"
            required
            :rules="[{ required: true, message: '请填写行程介绍' }]"
          />
          <van-field
            label="行程详情"
            type="textarea"
            v-model="formData.text"
            name="text"
            placeholder="请填写行程详情"
            required
            rows="4"
            style="height: 130px"
            :rules="[{ required: true, message: '请填写行程详情' }]"
          />
          <van-field name="uploader" label="图文详情" required style="height: 290px">
            <template #input>
              <div style="display: flex; flex-wrap: wrap">
                <div class="img" v-for="(item, index) in selectImgList" :key="index">
                  <van-image style="margin: 5px" width="80" height="80" :src="item" />
                  <van-icon @click="delimg(item)" class="imgxx" name="cross" color="#fff" />
                </div>
                <van-image
                  v-if="selectImgList.length < 6"
                  @click="selectImg('two')"
                  width="80"
                  height="80"
                  :src="require('./img_png/add.jpg')"
                />
              </div>
            </template>
          </van-field>
          <van-field
            style="height: 60px"
            label="起始时间"
            is-link
            v-model="formData.startTime"
            name="startTime"
            @click="showTime('one')"
            placeholder="请选择起始时间"
            required
            :rules="[{ required: true, message: '请选择起始时间' }]"
          />
          <van-field
            style="height: 60px"
            label="结束时间"
            is-link
            v-model="formData.endTime"
            name="endTime"
            @click="showTime('two')"
            placeholder="请选择结束时间"
            required
            :rules="[{ required: true, message: '请选择结束时间' }]"
          />
          <van-field
            label="其它说明"
            type="textarea"
            v-model="formData.remark"
            name="remark"
            placeholder="请填写其它说明信息"
            rows="4"
            style="height: 130px"
          />
        </van-cell-group>
        <div
          v-if="formData.id"
          style="
            display: flex;
            width: 90%;
            margin: 10px auto;
            align-items: center;
            justify-content: space-around;
          "
        >
          <div style="width: 45%">
            <van-button round block type="warning" @click="del"> 删除 </van-button>
          </div>
          <div style="width: 45%">
            <van-button round block color="#36c2a8" native-type="submit"> 提交 </van-button>
          </div>
        </div>
        <div style="margin: 20px" v-else>
          <van-button square block color="#36c2a8" native-type="submit"> 提交 </van-button>
        </div>
        <div style="height: 30px"></div>
      </van-form>
    </div>
    <van-popup
        v-model="showPopup"
        position="right"
        :style="{ width: '75%', height: '100%' }"
        @click-overlay="closePopup"
        :lock-scroll="false"
        close-on-popstate
      >
        <div
          style="
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 40px;
            background: #56d7d6;
          "
        >
          <van-search
            @clear="onRefresh"
            @search="onRefresh"
            margin="0 10px 20px 10px"
            height="40px"
            shape="round"
            :showAction="false"
            placeholder="搜索行程图片信息"
            background="#56D7D6"
            v-model="imgName"
          ></van-search>
        </div>
        <van-pull-refresh class="pull-refresh" v-model="refreshing" @refresh="onRefresh">
          <van-empty
            v-if="imageList.length == 0 && !error"
            image="search"
            description="未找到数据"
          />
          <van-empty v-if="error" image="error" description="网络错误" />
          <van-list
          style="margin-top: 50px;"
         :immediate-check="false"
        :loading="loading"
        :finished="finished"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        finished-text="没有更多了"
        @load="queryList"
        >
            <div class="ulbox">
              <div
                class="ul"
                v-for="(item, index) in imageList"
                :key="index"
                :style="{ border: item.check ? '2px solid #36c2a8' : '' }"
              >
                <div class="li" @click="checkImg(item)">
                  <div
                    style="
                      display: flex;
                      flex-direction: column;
                      align-items: center;
                      justify-content: space-around;
                    "
                  >
                    <div style="font-size: 18px; font-weight: 500">
                      {{ item.name }}
                    </div>
                    <div>
                      <van-image :src="item.image" mode="" height="160px" width="220px" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <template #error>
              <div class="error-tip" @click="retryLoad">
                <van-icon name="warning" />
                <span>加载失败，点击重试</span>
              </div>
            </template>
          </van-list>
        </van-pull-refresh>
        <div class="bottomButton">
          <div class="bottomButtonLeft">
            <van-button square block type="warning" @click="closePopup"> 取消 </van-button>
          </div>
          <div class="bottomButtonRight">
            <van-button square block color="#36c2a8" @click="addImg"> 确认 </van-button>
          </div>
        </div>
      </van-popup>
     <van-popup v-model="showDatePick" position="bottom">
          <van-datetime-picker
            :min-date="minDate"
            @confirm="onConfirm"
            @cancel="showDatePick = false"
            v-model="currentDate"
            type="date"
            title="选择年月日"
          />
        </van-popup>
  </div>
</template>

<script>
import {
  updateConvalesceActivityBack,
  deleteConvalesceActivityBack,
  queryImageLibrary
} from "@/api/realAssets/icsharedstation/LYDJ/index.js"
import moment from "moment"
import { Dialog, Toast } from "vant"

export default {
  data() {
    return {
      title: "行程信息",
      siteData: JSON.parse(localStorage.getItem("siteData")),
      timeType: "",
      showDatePick: false,
      minDate: new Date(moment().year(), 0, 1), // 最小日期
      currentDate: new Date(),
      showPopup: false,
      imgName: "",
      formData: {
        name: "",
        description: "",
        convalesceType: "",
        startTime: "",
        endTime: "",
        images: "",
        image: "",
        text: "",
        siteId: JSON.parse(localStorage.getItem("siteData")).id,
        remark: ""
      },
      pageData: {
        pageNumber: 1,
        pageSize: 10
      },
      imageList: [],
      selectImgOne: "",
      selectImgList: [],
      loading: false,
      finished: false,
      refreshing: false,
      error: false, // 控制错误状态
      checkType: false
    }
  },
  methods: {
    showTime (val) {
      this.showDatePick = true
      if (val == "one") {
        this.timeType = "one"
      } else if (val == "two") {
        this.timeType = "two"
      }
    },
    onConfirm (val) {
      let date = moment(val).format("YYYY-MM-DD")
      if (this.timeType == "one") {
        this.formData.startTime = date
      } else if (this.timeType == "two") {
        this.formData.endTime = date
      }
      this.showDatePick = false
    },
    onSubmit () {
      this.formData.images = this.selectImgList.join(",")
      console.log(this.formData);
      updateConvalesceActivityBack(this.formData).then((res) => {
        if (res.resultMessage == "SUCCESS") {
          Toast("提交成功")
          this.$router.push({
            path: "/HT/pages/LYDJ/list"
          })
        } else {
          Toast("提交失败")
        }
      })
    },
    delimg(val) {
      this.selectImgList = this.selectImgList.filter((item) => item !== val)
    },
    queryList() {
      this.loading = true
      if (this.error) return // 如果当前是错误状态，不自动触发加载
      if (this.refreshing) {
        this.imageList = []
      }
      queryImageLibrary({
        siteId: this.siteData.id,
        pageNumber: this.pageData.pageNumber,
        pageSize: this.pageData.pageSize,
        name: this.imgName
      })
        .then((res) => {
          if (res.resultMessage != "SUCCESS") {
            this.imageList = []
            this.error = true // 显示错误提示
          } else if (res.data.length == 0) {
            this.imageList = []
            this.finished = true
          } else {
            let dataList = res.data.map((item) => {
              item.check = false
              this.selectImgList.forEach((item2) => {
                if (item2 == item.image) {
                  item.check = true
                }
              })
              return item
            })
            this.imageList = [...this.imageList, ...dataList]
          }

          this.loading = false
          // 判断是否已加载完所有数据
          if (this.imageList.length == res.pageNum) {
            this.finished = true
          } else {
            this.pageData.pageNumber++
          }
          this.refreshing = false
        })
        .catch((err) => {
          console.log(err)
        })
    },
    closePopup() {
      this.showPopup = false
      this.pageData.pageNumber = 1
      this.pageData.pageSize = 10
      this.finished = false
      this.error = false
      this.loading = true
      this.refreshing = true
    },
    addImg () {
      let imgDataList = []
      if (this.selectImgOne) {
        this.formData.image = this.selectImgOne
      }
      if (this.checkType) {
        this.imageList.forEach((item) => {
          item.check && imgDataList.push(item.image)
        })
      }
      if (imgDataList.length > 0 && this.selectImgList.length < 6) {
        this.selectImgList = imgDataList
      } else if (this.selectImgList.length >= 6){
        Toast("最多选择6张图片")
      }
      this.closePopup()
    },
    selectImg (val) {
      this.imageList = []
      if (val == "one") {
        this.checkType = false
      } else if (val == "two") {
        this.checkType = true
      }
      this.showPopup = true
      this.queryList()
    },
    checkImg(val) {
      if (this.checkType) {
        val.check = !val.check
      } else {
        this.imageList.forEach((item) => {
          if (item.image == val.image) {
            item.check = true
            this.selectImgOne = val.image
          } else {
            item.check = false
          }
        })
      }
    },
    onClickLeft() {
      this.$router.push({
        path: "/HT/pages/LYDJ/list"
      })
    },
    del() {
      Dialog.confirm({
        title: "删除",
        message: "确认删除本条疗养信息吗"
      })
        .then(() => {
          deleteConvalesceActivityBack({
            id: this.formData.id
          }).then((res) => {
            this.$router.push({
              path: "/HT/pages/LYDJ/list"
            })
          })
        })
        .catch(() => {})
    },
    onRefresh() {
      this.imageList = []
      this.pageData.pageNumber = 1
      this.pageData.pageSize = 10
      this.finished = false
      this.error = false
      this.loading = true
      this.refreshing = true
      this.queryList()
    },
    retryLoad() {
      this.error = false
      this.loading = true
      this.queryList()
    }
  },
  mounted() {
    let arrayString = this.$route.query.HDXQ
    // 如果参数存在，则进行解码和解析
    if (arrayString) {
      // 解码并转换回数组
      let receivedArray = JSON.parse(decodeURIComponent(arrayString))
      this.formData = receivedArray
      receivedArray.images.length && (this.selectImgList = receivedArray.images.split(","))
    }
  }
}
</script>

<style lang="less" scoped>
@import "../../../../pagesNew/QNY/qny.less";
.content {
  background-color: #f8fbff;
}
.img {
  position: relative;
  .imgxx {
    position: absolute;
    right: 0px;
    top: 0px;
    background: #000;
  }
}
.van-field__error-message {
  height: 20px; /* 固定高度 */
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.titletopXX {
  height: 45px;
}
.bottomButton {
  display: flex;
  justify-content: space-between;
  padding: 5px 5px 0px 5px;
  height: 60px;
}
.bottomButtonLeft {
  width: 45%;
}
.bottomButtonRight {
  width: 45%;
}
</style>
